<template>
  <div class="todoapp">
    <TodoHeader :arr="list" @createTask="onCreateTask"></TodoHeader>
    <TodoMain @delList="delList" :arr="filterList"></TodoMain>
    <TodoFooter
      :arr="list"
      :isActive="isActive"
      @onClear="onClear"
      @setActive="setActive"
    ></TodoFooter>
  </div>
</template>

<script>
import TodoFooter from "./components/TodoFooter.vue";
import TodoHeader from "./components/TodoHeader.vue";
import TodoMain from "./components/TodoMain.vue";
export default {
  data() {
    return {
      isActive: "all",
      list: JSON.parse(localStorage.getItem("list")) || [],
    };
  },
  components: {
    TodoFooter,
    TodoHeader,
    TodoMain,
  },
  created() {},

  methods: {
    onCreateTask(task) {
      const id = this.list.length
        ? this.list[this.list.length - 1].id + 1
        : 100;
      this.list.push({
        id,
        name: task,
        isDone: false,
      });
    },
    onClear(undone) {
      this.list = undone;
    },
    setActive(active) {
      this.isActive = active;
    },
    delList(id) {
      const index = this.list.findIndex((item) => item.id === id);
      this.list.splice(index, 1);
    },
  },
  computed: {
    filterList() {
      if (this.isActive === "ondone") {
        return this.list.filter((item) => !item.isDone);
      }
      if (this.isActive === "done") {
        return this.list.filter((item) => item.isDone);
      }
      return this.list;
    },
  },
  watch: {
    list: {
      deep: true,
      handler() {
        localStorage.setItem("list", JSON.stringify(this.list));
      },
    },
  },
};
</script>

<style scoped></style>
